package com.win.controller.flume;

import com.jcraft.jsch.*;
import com.win.pojo.vo.Useruploadlog;
import com.win.service.UseruploadlogService;
import com.win.utils.Result;
import org.apache.tomcat.util.http.fileupload.FileItemIterator;
import org.apache.tomcat.util.http.fileupload.FileItemStream;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/uploadToLinux")
@CrossOrigin
public class FileUploadController {

    @Autowired
    private SftpService sftpService;
    @Autowired
    private UseruploadlogService logService;

    private static final String UPLOAD_DIRECTORY = "/root/project/happiness/"; // 远程SFTP目录

    @PostMapping("/{username}")
    public Result handleFileUpload(@RequestParam("file") MultipartFile file,@PathVariable String username) {
        try {
            InputStream inputStream = file.getInputStream();
            String remoteFilePath = UPLOAD_DIRECTORY + file.getOriginalFilename();
            sftpService.uploadFile(inputStream, remoteFilePath);

            //添加上传文件日志
            String uploadFileName = file.getOriginalFilename();
            Useruploadlog log = new Useruploadlog();
            log.setUsername(username);
            log.setFileName(uploadFileName.split("\\.")[0]);
            log.setFileType(uploadFileName.split("\\.")[1]);
            logService.addLog(log);

            return Result.ok(null);
        } catch (Exception e) {
            // 处理异常，返回错误响应
            return Result.ok(null);
        }
    }
}